<template>
  <div class="app-container">
    <div v-if="isShowSearchBtn" class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="title" label="关键字">
          <el-input
            v-model="queryParams.title"
            placeholder="角色名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-select
            v-model="queryParams.is_hid"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['role@add']"
              type="success"
              @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['role@del']"
              type="danger"
              v-if="removeIds.length > 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-button
              class="ml-3"
              @click="handleSearchShowBtn"
              icon="Search"
              circle
            />
            <el-button
              class="ml-3"
              title="刷新"
              @click="handleQuery"
              icon="Refresh"
              circle
            />
          </div>
        </div>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="ID"
          align="center"
          prop="id"
          width="100"
          sortable="custom"
        />
        <el-table-column label="角色名称" prop="title" />
        <el-table-column label="角色标识" prop="identify" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.is_hid === 0" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['role@edit']"
              type="primary"
              circle
              @click="openDialog(scope.row.id)"
              title="编辑"
            >
              <i-ep-edit />
            </el-button>
            <el-button
              v-hasPerm="['role@del']"
              type="danger"
              circle
              title="删除"
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.p"
        v-model:limit="queryParams.limit"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="40%"
      @close="closeDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级" prop="pid">
          <el-cascader
            v-model="formData.pid"
            :options="roleOptions"
            :props="cascaderProps"
            @change="cascaderCheck"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.title" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色标识" prop="code">
          <el-input v-model="formData.identify" placeholder="请输入角色标识" />
        </el-form-item>

        <el-form-item label="数据权限" prop="dataScope">
          <el-card style="width: 90%">
            <el-scrollbar v-loading="loading" max-height="180px">
              <el-tree
                node-key="value"
                v-model="formData.menu_ids"
                show-checkbox
                :data="menuList"
                :default-checked-keys="selectedRows"
                :default-expand-all="false"
                @check="checkTree"
                style="width: 90%"
              >
                <template #default="{ data }">
                  {{ data.label }}
                </template>
              </el-tree>
            </el-scrollbar>
          </el-card>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="formData.remark"
            placeholder="请输入备注"
          />
        </el-form-item>

        <el-form-item label="状态" prop="is_hid">
          <el-radio-group v-model="formData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {
  addRole,
  deleteRoles,
  getRoleForm,
  getRoleOptions,
  getRolePage,
  updateRole,
} from "@/api/role";
import { getData } from "@/api/menu";
import { RoleForm, RolePageVO, RoleQuery } from "@/api/role/types";
import { MenuVO } from "@/api/menu/types";

defineOptions({
  name: "Role",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const roleFormRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);
const isShowSearchBtn = ref(false);
const removeIds = ref([]); // 删除ID集合 用于批量删除
const selectedRows = ref([]);
const queryParams = reactive<RoleQuery>({
  p: 1,
  limit: 10,
});

const cascaderProps = ref({
  checkStrictly: true,
});
const roleList = ref<RolePageVO[]>();

const roleOptions = ref<OptionType[]>(); // 角色下拉数据源
const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<RoleForm>({
  id: undefined,
  pid: 0,
  sort: 0,
  is_hid: 0,
});

const rules = reactive({
  title: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  identify: [{ required: true, message: "请输入角色标识", trigger: "blur" }],
  menu_ids: [{ required: true, message: "请选择数据权限", trigger: "blur" }],
  is_hid: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

const menuList = ref<MenuVO[]>([]);
const orgTreeData = ref<OptionType[]>(); //组织架构下拉数据源
const defaultProps = ref({
  children: "children",
  label: "title",
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getRolePage(queryParams)
    .then(({ data }) => {
      roleList.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 打开角色表单弹窗 */
function openDialog(roleId?: number) {
  dialog.visible = true;
  loadRoleOptions();
  // 获取所有的菜单
  getData().then((response) => {
    menuList.value = response.data;
  });
  if (roleId) {
    dialog.title = "修改角色";
    getRoleForm(roleId).then(({ data }) => {
      Object.assign(formData, data);
      selectedRows.value = formData.menu_ids;
    });
  } else {
    dialog.title = "新增角色";
  }
}

/** 角色保存提交 */
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        updateRole(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addRole(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  selectedRows.value = [];
  formData.id = undefined;
  formData.menu_ids = [];
  formData.title = "";
  formData.identify = "";
  formData.sort = 0;
  formData.is_hid = 0;
  handleQuery();
}

/** 删除角色 */
function handleDelete(roleId?: number) {
  const roleIds = roleId || removeIds.value;
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteRoles({ ids: roleIds })
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleOptions.value = response.data;
  });
}

function cascaderCheck(data: any) {
  if (data.length > 0) {
    formData.pid = data[data.length - 1];
  } else {
    formData.pid = 0;
  }
}

function checkTree(nodeObj: any, data: any) {
  formData.menu_ids = data.checkedKeys;
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
});
</script>
